package com.mall.controller;


import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mall.domain.dto.SearchForm;
import com.mall.domain.response.Response;
import com.mall.domain.vo.UserRoleVO;
import com.mall.service.UserRoleService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user-role")
public class UserRoleController {

    @Resource
    private UserRoleService userRoleService;


    /**
     * 获取用户列表，支持分页和多条件搜索
     */
    @GetMapping("/selectAll")
    public Response<IPage<UserRoleVO>> getUserList(
            SearchForm searchForm,
            @RequestParam(defaultValue = "1") Integer page,
            @RequestParam(defaultValue = "10") Integer size) {

        // 调用服务层获取分页数据
        IPage<UserRoleVO> userPage = userRoleService.getUserList(searchForm, page, size);

        // 封装成统一响应格式返回
        return Response.success(userPage);
    }

    /**
     * 为用户分配角色
     */
    @PostMapping("/{userId}/assign-roles")
    public Response<?> assignRole(
            @PathVariable String userId,
            @RequestBody RoleAssignRequest request) {

        try {
            // 调用服务层处理角色分配逻辑
            userRoleService.assignRoleToUser(userId, request.getRoleId());
            // 返回成功响应
            return Response.success("角色分配成功");
        } catch (Exception e) {
            // 记录异常日志
            // log.error("角色分配失败", e);
            // 返回失败响应
            return Response.fail("角色分配失败：" + e.getMessage());
        }
    }

    public static class RoleAssignRequest {
        private String roleId; // 角色ID，可为null

        // getter和setter
        public String getRoleId() {
            return roleId;
        }

        public void setRoleId(String roleId) {
            this.roleId = roleId;
        }
    }


}
